package com.geping.etl.common.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.geping.etl.common.entity.Logs;
import com.geping.etl.common.entity.Sys_Subject;
import com.geping.etl.common.repository.Sys_SubjectRepository;
import com.geping.etl.common.service.LogsService;
import com.geping.etl.common.service.LogsSynService;
import com.geping.etl.common.util.Constants;
import com.geping.etl.config.Schedules;
import com.geping.etl.utils.EnvUitl;
import com.geping.etl.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.*;

@Service
@Slf4j
public class LogsSynServiceImpl implements LogsSynService {

    private final static Logger LOGGER = LoggerFactory.getLogger(Schedules.class);

    @Autowired
    private LogsService logsService;

    @Autowired
    private Sys_SubjectRepository sys_SubjectRepository;


    @Override
    public void updateLogs() {
        List<Sys_Subject> allSubjects = sys_SubjectRepository.findAllSubject();
        if (CollectionUtils.isEmpty(allSubjects)) {
            return;
        }
        for (Sys_Subject sysSubject : allSubjects) {
            try {
                tryPullSubjectLog(sysSubject);
            } catch (Exception e) {
                log.error("tryPullSubjectLog error", e);
            }
        }
    }

    /**
     * 尝试拉取系统日志
     *
     * @param sysSubject
     */
    private void tryPullSubjectLog(Sys_Subject sysSubject) {
        Integer id = sysSubject.getId();
        if (id == 1 || id == 2) {
            return;
        }
        //1.获取日志地址
        String url = getUrl(id);
        //2.拉取日志
        String result = pullLog(sysSubject, url);
        //3.日志解析保存
        saveLog(sysSubject,result);
    }


    /**
     * 获取副包日志地址
     *
     * @param id
     * @return
     */
    private String getUrl(Integer id) {
        String url = EnvUitl.props.getProperty(id + "") != null ? EnvUitl.props.getProperty(id + "") : "";
        String blackIdStr = EnvUitl.props.getProperty("synlog.black.id") != null ? EnvUitl.props.getProperty("synlog.black.id") : "";
        String[] blackIds = blackIdStr.split(",");
        if (StringUtils.isBlank(url) || Arrays.asList(blackIds).contains(String.valueOf(id))) {
            LOGGER.info("scheduledUpdateLogs->url is  blank or id is sava blackList, url = {}, id = {}, blackIdStr = {}", url, id, blackIdStr);
            return "";
        }
        return url;
    }

    /**
     * 保存拉取的日志
     *
     * @param result
     */
    private void saveLog(Sys_Subject sysSubject,String result) {
        if (StringUtils.isBlank(result)) {
            return;
        }
        JSONArray jsonArray = JSONObject.parseArray(result);
        if (jsonArray != null && !jsonArray.isEmpty() && jsonArray.size() > 0) {
            for (int i = 0; i < jsonArray.size(); i++) {
                Logs logs = new Logs();
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                logs.setLogDate(jsonObject.get("logDate").toString());
                logs.setLogType(jsonObject.get("logType").toString());
                logs.setLoginId(jsonObject.get("loginId").toString());
                logs.setLogOrgCode(jsonObject.get("logOrgCode").toString());
                logs.setLogContent("【"+sysSubject.getSubjectName()+"】："+jsonObject.get("logContent").toString());
                logsService.save(logs);
            }
        }
    }

    /**
     * 拉取日志
     *
     * @param sys_subject
     * @return
     */
    private String pullLog(Sys_Subject sys_subject, String url) {
        if(StringUtils.isBlank(url)){
            return "";
        }
        String result = "";
        try {
            result = HttpUtil.updateLogs(url + Constants.updateLogs);
        } catch (Exception e) {
            log.error("pull log error,  url:{},id:{},name:{}  log error", url, sys_subject.getId(), sys_subject.getSubjectName());
            log.error("pull error", e);
        }
        return result;
    }


}
